# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout as auth_logout
from web_app.models import UserUrl, UserUrlAdvert
from web_app.parser import process_search_url
from custom_exceptions import EmptyResultsTable
from web_app.calendar_client import Client
from django.core.exceptions import ObjectDoesNotExist


def index(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('add-url')
    else:
        return render_to_response(
            'index.html',
            {'menu_item': 'p1'},
            RequestContext(request)
        )


@login_required
@csrf_protect
def add_search_url(request):
    return render_to_response(
        'add_assistance.html',
        {'menu_item': 'p2', 'last_login': request.session.get('social_auth_last_login_backend')},
        RequestContext(request)
    )


def search_all():
    user_urls = UserUrl.objects.all()
    for user_url in user_urls:
        try:
            process_search_url(user_url, UserUrlAdvert)
        except EmptyResultsTable, e:
            continue


def research(request):
    search_all()
    return HttpResponse('success')


def send_all_notifications():
    not_processed_adverts = UserUrlAdvert.objects.filter(processed=False)
    if not_processed_adverts.count() > 0:
        client = Client()
    else:
        return HttpResponse('No events')
    for adv in not_processed_adverts:
        try:
            user_profile = adv.user_url.user.get_profile()
        except ObjectDoesNotExist:
            continue
        client.add_event_to_calendar(user_profile.calendar_id,
                                     u"Автомобиль по цене %d" % adv.advert_price)
        adv.processed = True
        adv.save()


def send_notifications(request):
    send_all_notifications()
    return HttpResponse('success')


def logout(request):
    """Logs out user"""
    auth_logout(request)
    return HttpResponseRedirect('/')